package mobileann.mafamily.utils;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import mobileann.mafamily.act.main.FS;
import mobileann.mafamily.entity.MemberInfoEntity;
import mobileann.mafamily.entity.UserInfoEntity;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.mobileann.mafamily.R;
import com.mofind.android.base.L;
import com.mofind.android.net.HttpUtils;
import com.mofind.android.net.HttpUtils.HttpResultCallback;
import com.mofind.android.net.JSONParser;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

/**
 * 添加一些注释
 * @change ADRIAN.20151023
 */
public class RdLoginManager {
	private UMSocialService mController ;
	private Activity context;
	private static String TAG="RdLoginManager";
	public static final String SMSKEY="da4cb3fee698";
	public static final String SMSSECRET="c37d0d9f75f2dc70bb109b5ccc80856a";
//	public static final String SMSKEY="a69a63191980";
//	public static final String SMSSECRET="5a324fae305fdc5fa7b0d26fba05cd74";
	private static final String REGISTER="register";
	private static final String SDK_CODE="sdk_code";

	public RdLoginManager(Activity context) {
		this.context = context;
		mController = UMServiceFactory
				.getUMSocialService("com.umeng.login");
		mController.getConfig().closeToast();
	}

	/**
	 * 调用第三方登陆，将Handler传入
	 * @param handler
	 * @annotation ADRIAN 2015.7.15.20.45
	 */
	public void doQQOauth(final Handler handler){
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(context, ShareUtil.QQ_APPID, ShareUtil.QQ_APPSECRET);// QQ的id和secret
		qqSsoHandler.addToSocialSDK();
		//	if(qqSsoHandler.isClientInstalled()){
		getOAuthData(SHARE_MEDIA.QQ, handler, "qq",false);
		//	}else{
		//	    Toast.makeText(context, "请安装QQ客户端", Toast.LENGTH_SHORT).show();
		//	}
	}
	public void doWXOauth(Handler handler){
		String id = ShareUtil.WECHAT_APPID;// 微信的id
		String secret = ShareUtil.WECHAT_APPSECRET;// 微信的secret
		UMWXHandler wxHandler = new UMWXHandler(context, id, secret);
		wxHandler.addToSocialSDK();
		if(wxHandler.isClientInstalled()){
			getOAuthData(SHARE_MEDIA.WEIXIN, handler, "weixin",false);
		}else{
			Toast.makeText(context, "请安装微信客户端", Toast.LENGTH_SHORT).show();
		}
	}
	public void doSinaOauth(final Handler handler){
		mController.getConfig().setSsoHandler(new SinaSsoHandler());//设置新浪SSO handler
		getOAuthData(SHARE_MEDIA.SINA, handler, "weibo",true);
	}

	public void deleteOauth(final SHARE_MEDIA platform) {
		if (mController != null) {
			mController.deleteOauth(context, platform,
					new SocializeClientListener() {

				@Override
				public void onStart() {

				}

				@Override
				public void onComplete(int arg0, SocializeEntity arg1) {
					if (arg0 == 200) {
						Toast.makeText(context, "删除成功.",Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

	public UMSocialService getOAuthController() {
		return this.mController;
	}
	/**
	 * 2015.7.15.20.19.应该是第三方登录信息获取
	 * 2015.7.15.20.23.点击QQ登录的图标，就会调用此方法，登录成功或失败后有回调方法。
	 * 
	 * @param platform
	 * @param handler
	 * @param type      2015.7.15.20.43.有三种第三方登录的情况(doQQQauth,doSinaOauth,doWXOauth),传过不同的type
	 * @param isWeb
	 * @annotation ADRIAN 
	 */
	private void getOAuthData(SHARE_MEDIA platform,final Handler handler,final String type,final boolean isWeb){
		mController.doOauthVerify(context, platform, new UMAuthListener() {
			@Override
			public void onStart(SHARE_MEDIA platform) {
				L.i(TAG, "授权开始");
			}
			@Override
			public void onError(SocializeException e, SHARE_MEDIA platform) {
				Toast.makeText(context,platform.toString()+"平台授权错误", Toast.LENGTH_SHORT).show();
			}
			@Override
			public void onComplete(Bundle value, SHARE_MEDIA platform) {
				String access=value.getString("access_token");
				String refresh=null;
				refresh=value.getString("refresh_token");
				String openid;
				if(isWeb){
					openid=value.getString("uid");
				}else{
					openid=value.getString("openid");
				}
				String expires=value.getString("expires_in");
				if(!TextUtils.isEmpty(openid)){
					doRdLogin(System.currentTimeMillis()/1000+"", type, openid, access, expires,refresh,handler,type);
				}
				SPUtils.setRdLoginAccess(access);
				SPUtils.setRdLoginExpires(expires);
				SPUtils.setRdLoginOpenId(openid);
				SPUtils.setRdLoginRefresh(refresh);
				//获取相关授权信息
				//		    if(!isWeb){
				mController.getPlatformInfo(context, platform, new UMDataListener() {
					@Override
					public void onStart() {
						L.i(TAG, "获取平台数据开始...");
					}                                              
					@Override
					public void onComplete(int arg0, Map<String, Object> info) {
						if(arg0 == 200 && info != null){
//							String nickName=(String) info.get("screen_name");
//							String imagUrl=(String) info.get("profile_image_url");
						}else{
							L.d(TAG,"发生错误："+arg0);
						}
					}
				});
				//        		    }
			}
			@Override
			public void onCancel(SHARE_MEDIA platform) {
//				Log.i(TAG,"授权取消");
			}
		} );
	}
	
	/**
	 * 2015.7.15.20.18.第三方登录时，调用此方法访问服务器
	 * 
	 * @param ut        2015.7.15.20.40.当前的时间
	 * @param type      2015.7.15.20.40.从上边传过来的type
	 * @param openId    2015.7.15.20.40.getOAuthData的openId
	 * @param access    2015.7.15.20.40.getOAuthData的access_token
	 * @param expires   2015.7.15.20.40.getOAuthData的expires_in
	 * @param refresh   2015.7.15.20.40.getOAuthData的refresh_token
	 * @param handler   2015.7.15.20.40.需要传输数据的handler（将用Handler传回）
	 * @param logintype 2015.7.15.20.40.登录的类型
	 * @annotation ADRIAN 
	 */
	public void doRdLogin(final String ut,String type,String openId,String access,String expires,String refresh,final Handler handler,final String logintype){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getRdLoginPara(ut, type, openId, access, expires, refresh), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if(isResult){
					LoginUtils.getInstance().setLoginData(ut, jsonStr, handler,logintype);
				}
			}
		});
	}
	private Map<String, String> getRdLoginPara(String ut,String type,String openId,String access,String expires,String refresh) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", "register");
		map.put("ut", ut);
		map.put("data", jsonData(ut, type, openId, access, expires, refresh));
		return map;
	}
	private String jsonData(String ut,String type,String openId,String access,String expires,String refresh){
		Map<String, String> map = new HashMap<String, String>();
		map.put("channel", PhoneInfoUtils.getVersionChannel(FS.getInstance()));
		map.put("version", PhoneInfoUtils.getVersionCode(FS.getInstance()));
		map.put("type", type);
		map.put("open_id", openId);
		map.put("refresh_token", refresh);
		map.put("access_token", access);
		map.put("expires_in", expires);
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(ut,"register", data);
	}
	//使用sharesdk的短信登录
	public void doSMSLogin(final Context c,final Handler handler,final String ut,String phone,String code){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getAbroadSMSPara(ut, phone, code), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if(isResult){
					String json = TripleDESUtil.getJsonObjStr(ut, REGISTER,
							jsonStr);
					if(TextUtils.isEmpty(json)){
					}else{
						JSONObject jo = JSONParser.getJSONObject(json);
						String status = JSONParser.getString(jo, "status");
						if (!TextUtils.isEmpty(status)) {
							String reason=JSONParser.getString(jo, "reason");
							String reaStr=null;
							if(TextUtils.isEmpty(reason)){
								reaStr=c.getString(R.string.abroad_verifycode_error1);
							}else{
								if("code".equals(reason)){
									reaStr=c.getString(R.string.rdlogin_error1);
								}else if("other".equals(reason)){
									reaStr=c.getString(R.string.rdlogin_getcode_error5);;
								}else if("check_limit".equals(reason)){
									reaStr=c.getString(R.string.abroad_verifycode_error2);
								}else {
									reaStr="ERROR";
								}
							}
							if(handler!=null)
								handler.obtainMessage(LoginUtils.LOGIN_ERROR,reaStr).sendToTarget();
						} else {
							String uid = JSONParser.getString(jo, "uid");
							String name = JSONParser.getString(jo, "name");
							String urad = JSONParser.getString(jo, "urad");
							String fid = JSONParser.getString(jo, "fid");
							String frad = JSONParser.getString(jo, "frad");
							String role = JSONParser.getString(jo, "role");
							String avatar = JSONParser.getString(jo, "avatar"); 
							String irad = JSONParser.getString(jo, "irad");
							String lockpwd = JSONParser.getString(jo, "lockpwd");
							String phone=JSONParser.getString(jo, "phone");
							//new 推荐码
							String referee_code = JSONParser.getString(jo, "referee_code");
							SPUtils.setRefereeCode(uid, referee_code);
							MemberInfoEntity entity = new MemberInfoEntity(uid, urad,
									name, role, phone, avatar);
							entity.setFrad(frad);
							entity.setFid(fid);
							entity.setIrad(irad);
							if (lockpwd != null) {
								entity.setLockpwd(lockpwd);
							}
							SPUtils.saveMySelf(entity);
							// 为使用老版本加入
							UserInfoEntity userInfo = new UserInfoEntity();
							userInfo.setUid(phone);
							userInfo.setFid(fid);
							userInfo.setNickname(name);
							userInfo.setTelephone(phone);
							userInfo.setRole(Integer.valueOf(role));
							if (lockpwd != null) {
								userInfo.setScLockPwd(lockpwd);
							}
							SPUtils.saveSelf(userInfo);
							FS.getInstance().self().setTelephone(phone);
							FS.getInstance().self().setUid(phone);
							FS.getInstance().self().setRole(Integer.parseInt(role));
							FS.getInstance().self().setNickname(name);
							FS.getInstance().self().setFid(fid);
							MemberListUtils.getInstance().setCurrentUser(userInfo);
							SPUtils.setLoginType(uid, "phone");
							if(handler!=null)
								handler.obtainMessage(LoginUtils.LOGIN_SUCCESS).sendToTarget();
						}
					}
				}
			}
		});
	}
	private Map<String, String> getAbroadSMSPara(String ut,String phone,String code) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", REGISTER);
		map.put("ut", ut);
		map.put("data", jsonSMSData(ut, phone, code));
		return map;
	}
	/**
	 * 验证码登录注册时上传的数据
	 * @param ut 时间戳
	 * @param phone 手机号
	 * @param code 验证码
	 * @param sdk 验证码sdk包名称（share sdk 大陆地区安卓取1,iOS取2，海外地区安卓取3,iOS取4）
	 * @param zone 来自国家地区区号大陆地区不需要填写
	 * @return
	 */
	private String jsonSMSData(String ut,String phone,String code){
		Map<String, String> map = new HashMap<String, String>();
		map.put("channel", PhoneInfoUtils.getVersionChannel(FS.getInstance()));
		map.put("version", PhoneInfoUtils.getVersionCode(FS.getInstance()));
		map.put("type", "phone");
		map.put("phone", phone);
		map.put("code", code);
		map.put("sdk", "9");
		map.put("sdk_version", "2.0");
//		if(SPUtils.getIsVoiceCode()){
//			map.put("sdk", "5");
//		}else{
//			map.put("sdk", "1");
//		}
		map.put("zone", "86");
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(ut,REGISTER, data);
	}
	
	/***/
	public void doResponseCode(final Context c,final String ut,String phone,String response){
		HttpUtils.startHttpPost(URLUtils.URL_GROWTH_UPLOAD, getSDKPara(ut, phone,response), new HttpResultCallback() {

			@Override
			public void result(String url, boolean isResult, String jsonStr) {
				if(isResult){
					String json = TripleDESUtil.getJsonObjStr(ut, SDK_CODE, jsonStr);
					if(!TextUtils.isEmpty(json)){
						JSONObject jo = JSONParser.getJSONObject(json);
						String status = JSONParser.getString(jo, "status");
						if("true".equalsIgnoreCase(status)){
							
						}else{
//							String reason = JSONParser.getString(jo, "reason");
//							Toast.makeText(context, reason, Toast.LENGTH_SHORT).show();
						}
					}
				}
			}
		});
	}
	private Map<String, String> getSDKPara(String ut,String phone,String response) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", SDK_CODE);
		map.put("ut", ut);
		map.put("data", jsonSDKData(ut, phone,response));
		return map;
	}
	/**
	 * 记录sdk发送验证码,调用sdk发送短信后需要调用该接口用于后台统计
	 * @param ut 时间戳
	 * @param phone 手机号
	 * @param zone 区号
	 * @param sdk sdk包名
	 * @param response 接口返回值
	 * @return
	 */
	private String jsonSDKData(String ut,String phone,String response){
		Map<String, String> map = new HashMap<String, String>();
		map.put("phone", phone);
		map.put("zone", "86");
		map.put("sdk", "9");
//		if(SPUtils.getIsVoiceCode()){
//			map.put("sdk", "5");
//		}else{
//			map.put("sdk", "1");
//		}
		map.put("response", response);
		String data = MyTaskUtils.getInstance().map2json(map);
		return TripleDESUtil.CBCEncode(ut,SDK_CODE, data);
	}
}
